package com.pointstar.dp.common.utils;

import com.pointstar.dp.common.support.properties.GlobalProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * 文件上传下载工具类
 * @author zhukerui
 */
@DependsOn("springContextUtils")
public class UploadUtils {

    private static Logger LOG = LoggerFactory.getLogger(UploadUtils.class);

    private static GlobalProperties globalProperties = SpringContextUtils.getBean("globalProperties", GlobalProperties.class);

    /** 上传文件处理(支持批量) */
    public static List<String> uploadFile(HttpServletRequest request) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        List<String> fileNames = new ArrayList<>();
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            for (Iterator<String> iterator = multiRequest.getFileNames(); iterator.hasNext();) {
                String key = iterator.next();
                MultipartFile multipartFile = multiRequest.getFile(key);
                if (multipartFile != null) {
                    String name = multipartFile.getOriginalFilename();
                    String filePath = globalProperties.getUploadLocation() + name;
                    File file = new File(filePath);
                    file.setWritable(true, false);
                    try {
                        multipartFile.transferTo(file);
                        if (name != null) {
                            fileNames.add(globalProperties.getUploadMapping().concat(name));
                        }
                    } catch (Exception e) {
                        LOG.error(name + "保存失败", e);
                    }
                }
            }
        }
        return fileNames;
    }

    /** 上传文件处理(支持批量) */
    public static List<String> uploadFile(HttpServletRequest request, String path) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        List<String> fileNames = new ArrayList<>();
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            File dirFile = new File(globalProperties.getUploadLocation().concat(path));
            if (!dirFile.isDirectory()) {
                dirFile.mkdirs();
            }
            for (Iterator<String> iterator = multiRequest.getFileNames(); iterator.hasNext();) {
                String key = iterator.next();
                MultipartFile multipartFile = multiRequest.getFile(key);
                if (multipartFile != null) {
                    String name = multipartFile.getOriginalFilename();
                    String uuid = UUID.randomUUID().toString();
                    String postFix = null;
                    if (name != null) {
                        postFix = name.substring(name.lastIndexOf(".")).toLowerCase();
                    }
                    String fileName = uuid + postFix;
                    String filePath = globalProperties.getUploadLocation() + path + fileName;
                    File file = new File(filePath);
                    file.setWritable(true, false);
                    try {
                        multipartFile.transferTo(file);
                        fileNames.add(globalProperties.getUploadMapping() + path + fileName);
                    } catch (Exception e) {
                        LOG.error(name + "保存失败", e);
                    }
                }
            }
        }
        return fileNames;
    }

    /**
     * 下载文件
     * @param path
     * @param response
     * @throws IOException
     */
    public static void downloadFile(String path, HttpServletResponse response) throws IOException {
        //1.获取要下载的文件名及其类型后缀
        String fileName = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
        String suffix = path.substring(path.lastIndexOf(".")).toLowerCase();
        //2.设置content-disposition响应头控制浏览器以下载的形式打开文件,并已UTF-8编码避免文件名中的中文出现乱码
        response.setHeader("Content-Disposition", "attachment;filename="+ java.net.URLEncoder.encode(fileName, "UTF-8")+ suffix);
        //3.获取要下载的文件输入流
        InputStream in=null;
        OutputStream out=null;
        try {
            in=new FileInputStream(path);
            int len;
             //4.创建数据缓冲区
             byte[] buffer = new byte[1024];
             //5.通过response对象获取OutputStream流
             out = response.getOutputStream();
             //6.将FileInputStream流写入到buffer缓冲区
             while ((len = in.read(buffer)) > 0) {
                 //in.read(byte[] b)最多读入b.length个字节 在碰到流的结尾时 返回-1
                 //7.使用OutputStream将缓冲区的数据输出到客户端浏览器
                 out.write(buffer,0,len);
             }
             out.flush();
         } finally{
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}
